package com.qcq.wecheck.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.qcq.wecheck.entity.Attendance;
import com.qcq.wecheck.entity.Schedule;
import com.qcq.wecheck.result.CommonResult;
import com.qcq.wecheck.service.AttendanceService;
import com.qcq.wecheck.service.ScheduleService;
import com.qcq.wecheck.service.UserScheduleService;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 签到记录表 前端控制器
 * </p>
 *
 * @author O
 * @since 2018-09-19
 */
@RestController
@RequestMapping("/attendance")
public class AttendanceController {
	@Resource
	private AttendanceService attendanceService;
	@Resource
	private UserScheduleService userScheduleService;
	@Resource
	private ScheduleService scheduleService;

	/**
	 * 参加考勤
	 */
	@PostMapping
	public CommonResult attend(@Validated Attendance attendance, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return CommonResult.failure(bindingResult.getFieldError().getDefaultMessage());
		}
		try {
			attendance.setCheckTime(LocalDateTime.now());
			attendanceService.insert(attendance);
			return CommonResult.success(attendance.getId());
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResult.failure("数据库添加失败");
		}
	}

	/**
	 * 分页获取指定考勤表的考勤记录
	 */
	@GetMapping
	public CommonResult get(@RequestParam("openId") String openId,
	                        @RequestParam("scheduleId") Long scheduleId,
	                        @RequestParam("pageNo") Integer pageNo,
	                        @RequestParam("pageSize") Integer pageSize) {
		Page<Attendance> page = new Page<>(pageNo, pageSize);
		EntityWrapper<Attendance> wrapper = new EntityWrapper<>();
		wrapper.eq("open_id", openId)
				.eq("schedule_id", scheduleId);
		return CommonResult.success(attendanceService.selectPage(page, wrapper));
	}

	/**
	 * 根据日期,openId和scheduleId获取特定考勤表的数量(考勤次数)
	 */
	@GetMapping("/count")
	public CommonResult getCount(@RequestParam("openId") String openId,
	                             @RequestParam("scheduleId") Long scheduleId,
	                             @RequestParam("date") String date) {
		LocalDate localDate;
		try {
			localDate = LocalDate.parse(date, DateTimeFormatter.ISO_DATE);
		} catch (Exception e) {
			return CommonResult.failure("日期格式错误, eg: 1998-01-18");
		}

		return CommonResult.success(attendanceService.getAttendanceCount(openId, scheduleId, localDate));
	}

	/**
	 * 根据日期段,openId和scheduleId获取特定考勤表的数量(考勤次数)
	 */
	@GetMapping("/count/dates")
	public CommonResult getCountByDates(@RequestParam("openId") String openId,
	                                    @RequestParam("scheduleId") Long scheduleId,
	                                    @RequestParam("from") String from,
	                                    @RequestParam("to") String to) {
		try {
			return CommonResult.success(attendanceService.getAttendanceCount(openId, scheduleId, from, to));
		} catch (Exception e) {
			return CommonResult.failure();
		}
	}

	/**
	 * 删除用户参与的签到活动(删除签到内容)
	 * 根据签到表的id和openId
	 */
	@DeleteMapping
	public CommonResult quit(@RequestParam("scheduleId") Long scheduleId,
	                         @RequestParam("openId") String openId) {
		try {
			userScheduleService.quitAndDeleteHistory(scheduleId, openId);
			return CommonResult.success();
		} catch (Exception e) {
			return CommonResult.failure("后台错误,请联系管理员");
		}
	}

	/**
	 * 签到统计
	 */
	@GetMapping("/combo")
	public CommonResult totalCount(@RequestParam("scheduleId") Long scheduleId,
	                               @RequestParam("openId") String openId) {
		Schedule schedule = scheduleService.selectById(scheduleId);
		if (schedule == null) {
			return CommonResult.failure("考勤表不存在");
		}
		return CommonResult.success(attendanceService.getCombo(schedule, openId));
	}

	/**
	 * 根据日期获取该日期具体考勤情况
	 */
	@GetMapping("/date")
	public CommonResult getByDate(@RequestParam("openId") String openId,
	                              @RequestParam("scheduleId") Long scheduleId,
	                              @RequestParam("date") String date) {
		try {
			List<String> attendances = attendanceService.getByDate(openId, scheduleId, date)
					.stream()
					.map(attendance -> attendance.getCheckTime().format(DateTimeFormatter.ofPattern("HH:mm:ss")))
					.collect(Collectors.toList());
			return CommonResult.success(attendances);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return CommonResult.failure();
	}
}

